package com.jinyi.wwdeng.ui.steps.act

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jinyi.base.utils.log.HHLog
import com.jinyi.lib_baseadapter.BGAOnItemChildClickListener
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActStepListBinding
import com.jinyi.wwdeng.pro.ProMvpAct
import com.jinyi.wwdeng.ui.main.act.CreditApplyAct
import com.jinyi.wwdeng.ui.permission.PermissionUtils
import com.jinyi.wwdeng.ui.steps.adapter.StepTabAdapter
import com.jinyi.wwdeng.ui.steps.contract.StepListContract
import com.jinyi.wwdeng.ui.steps.fragment.StepAccountFragment
import com.jinyi.wwdeng.ui.steps.fragment.StepCommonFragment
import com.jinyi.wwdeng.ui.steps.fragment.StepContactFragment
import com.jinyi.wwdeng.ui.steps.fragment.StepFaceFragment
import com.jinyi.wwdeng.ui.steps.fragment.StepOCRFragment
import com.jinyi.wwdeng.ui.steps.impl.StepListPresenterImpl
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/18 10:43
 * @Annotation：流程列表页面
 */
class StepListAct : ProMvpAct<StepListContract.View, StepListPresenterImpl>(),
    StepListContract.View {
    lateinit var binding: ActStepListBinding

    //广播接收器
    private var mRecevier: ProcessUpdatedRecevier? = null

    private var mTabAdapter: StepTabAdapter? = null
    override fun getRootView(): View {
        binding = ActStepListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): StepListPresenterImpl {
        return StepListPresenterImpl()
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setRightBtnRes(R.mipmap.pic_kefu_black_icon)
        initPresenter()

        registerUpdateRecevier()
        initRecyclerView()
    }

    override fun initListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(
                TrackEventType.CLICK.CLICK_CUSTOMER,
                "Information Step " + rootViewBinding.tvBaseTitle.text.toString() + " Page"
            )
        }
    }

    override fun initData() {
        presenter.loadStepDataListAction()
    }

    /* 权限请求监听 */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtils.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
    }

    /**
     * 初始化Tab列表
     */
    private fun initRecyclerView() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        mTabAdapter = StepTabAdapter(binding.recyclerView)
        binding.recyclerView.adapter = mTabAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        mTabAdapter!!.setOnItemChildClickListener(BGAOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        })
    }

    /**
     * 显示全部流程列表
     */
    override fun showStepTabList(dataList: ArrayList<JSONObject>, selectIndex: Int) {
        mTabAdapter!!.data = dataList
        if (selectIndex != -1) {
            setTextTitle(dataList[selectIndex].optString("tabTitle"))
            binding.recyclerView.post {
                binding.recyclerView.smoothScrollToPosition(selectIndex)
            }
        }
    }

    /**
     * 常规通用样式
     */
    override fun showCommonInfoPage(data: JSONObject) {
        replaceContainerFragement(R.id.contentLayout, StepCommonFragment(data))
    }

    /**
     * Contact联系人样式
     */
    override fun showContactInfoPage(data: JSONObject) {
        replaceContainerFragement(R.id.contentLayout, StepContactFragment(data))
    }

    /**
     * 证件照样式
     */
    override fun showOcrInfoPage() {
        replaceContainerFragement(R.id.contentLayout, StepOCRFragment())
    }

    /**
     * 人脸自拍样式
     */
    override fun showSelfieInfoPage() {
        replaceContainerFragement(R.id.contentLayout, StepFaceFragment())
    }

    /**
     * 绑定账号（法语）
     */
    override fun showAccountInfoFrenchPage() {
        replaceContainerFragement(R.id.contentLayout, StepAccountFragment())
    }

    /**
     * 进入贷款申请页面
     */
    override fun showCreditApplyPage() {
        onIntent(CreditApplyAct::class.java)
        Handler().postDelayed({
            finish()
        }, 500)
    }

    /**
     * 提交流程数据
     */
    fun onSubmitRequest(params: JSONObject) {
        HHLog.e("提交信息：$params")
        presenter.onSubmitStepAction(params)
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    override fun showStepSubmitSuccess() {
        val intent = Intent(AppConfigs.Action.ACTION_PROCESS_UPDATE)
        sendBroadcast(intent)
    }

    /**
     * 注册更新用户流程状态广播
     */
    private fun registerUpdateRecevier() {
        mRecevier = ProcessUpdatedRecevier(this)
        var intentFilter = IntentFilter()
        intentFilter.addAction(AppConfigs.Action.ACTION_PROCESS_UPDATED)//更新流程状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(mRecevier, intentFilter, Context.RECEIVER_EXPORTED)
        } else {
            registerReceiver(mRecevier, intentFilter)
        }
    }

    class ProcessUpdatedRecevier(act: StepListAct) : BroadcastReceiver() {
        var act = act
        override fun onReceive(context: Context, intent: Intent) {
            act.onRecevierEvent(intent)
        }
    }

    /**
     * 处理广播接收事件处理
     */
    private fun onRecevierEvent(intent: Intent) {
        //根据需求添加自己需要关闭页面的action
        when (intent.action) {
            AppConfigs.Action.ACTION_PROCESS_UPDATED -> {//更新流程状态
                HHLog.e("收到总流程刷新完成通知>>>>>>>>>>" + AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_PROCESS))
                presenter.loadStepDataListAction()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRecevier != null) {
            unregisterReceiver(mRecevier)
        }
    }
}